package com.wx.spider.mobile.controller;

import com.wx.spider.common.enums.MqMsgBean;
import com.wx.spider.common.model.CommonResponse;
import com.wx.spider.mobile.config.CloudConfig;
import com.wx.spider.mobile.socket.AppmsgWebSocket;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author:feng
 * @create:2021-04-26 16:26
 */
@RestController
@RequestMapping("/base")
public class BaseController {
    @Autowired
    private CloudConfig cloudConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AppmsgWebSocket appmsgWebSocket;

    @Autowired
    public RocketMQTemplate rocketMQTemplate;

    @GetMapping("/test")
    private CommonResponse test(){
        try {
            String port = cloudConfig.getPort();
            String username = cloudConfig.getUsername();
            return CommonResponse.succeed(username + ":" + port);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    @GetMapping("/socket")
    private CommonResponse socket(){
        try {
            appmsgWebSocket.sendMessageToFree("run");
            return CommonResponse.SUCCESS_RESPONSE;
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }

    @GetMapping("/startSocket")
    public CommonResponse<String> startSocket(String msg){
        try {
            msg = msg == null || "".equals(msg) ? "start tasks to free!" : msg;
            rocketMQTemplate.convertAndSend(MqMsgBean.PM_TO_MOBILE_SOCKET.getTopic(),msg);
            return CommonResponse.succeed(cloudConfig.getPort());
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResponse.INTERNAL_ERROR_RESPONSE;
        }
    }
}
